package com.linked.usermanage.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linked.commonentity.usermanage.log.LoginLogEnum;
import com.linked.usermanage.login.bean.po.LoginLogPO;
import com.linked.usermanage.login.bean.po.LoginPO;
import com.linked.usermanage.login.mapper.ILoginLogMapper;
import com.linked.usermanage.login.mapper.ILoginMapper;
import com.linked.usermanage.login.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;


/**
 * @author :dbq
 * @date : 2022/9/23 16:59
 */
@Service
public class LoginServiceImpl implements ILoginService {

    private final ILoginMapper loginMapper;

    private final ILoginLogMapper loginLogMapper;

    @Autowired
    public LoginServiceImpl(ILoginMapper loginMapper, ILoginLogMapper loginLogMapper) {
        this.loginMapper = loginMapper;
        this.loginLogMapper = loginLogMapper;
    }

    @Override
    public LoginPO queryPassword(String username) throws Exception {
        return loginMapper.queryPassword(username);
    }

    @Override
    public boolean saveLoginInfo(LoginPO loginPO) throws Exception {
        if (checkUsernameUsed(loginPO.getUsername())) {
            return false;
        }
        //这个是盐  29个字符，随机生成
        String gensalt = BCrypt.gensalt();
        loginPO.setPassSalt(gensalt);
        //根据盐对密码进行加密
        String password = BCrypt.hashpw(loginPO.getPassword(), gensalt);
        loginPO.setPassword(password);
        try {
            loginLogMapper.insert(LoginLogPO.Builder().withUsername(loginPO.getUsername()).withLogType(LoginLogEnum.SAVE));
        } catch (Exception e) {

        }
        return loginMapper.insert(loginPO) > 0;
    }

    @Override
    public boolean checkUsernameUsed(String username) throws Exception {
        return loginMapper.findUsernameUsed(username) > 0;
    }

    @Override
    public LoginPO findLoginInfo(String loginName) {
        QueryWrapper<LoginPO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginName);
        wrapper.last("LIMIT 1");
        return loginMapper.selectOne(wrapper);
    }
}
